package com.karrim.server.io.sql.util;

import com.karrim.server.util.Util;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author andrea.cantafio
 */
public class Table {

    public Table(String name) {
        this(name, new ArrayList<Field>());
    }

    public Table(String name, List<Field> fields) {
        this.fields = fields;
        this.name = name;
    }

    public boolean addField(Field f) {
        return fields.add(f);
    }

    public String getDefinition() {
        String ddl = "CREATE TABLE " + name + " (";
        if (fields.isEmpty()) {
            return ddl + ");";
        }
        for (Field f : fields) {
            ddl += f.getName() + " " + f.getType() + (f.isNullable() ? " " : " NOT ") + "NULL" + DELIMITER;
        }
        ddl = ddl.substring(0, ddl.length() - DELIMITER.length());
        return Util.sanitize(ddl.substring(0, ddl.length() - DELIMITER.length() + 1).concat(");"));
    }

    public Field getField(int index) throws IndexOutOfBoundsException {
        return fields.get(index);
    }

    public boolean removeField(Field f) {
        return fields.remove(f);
    }

    public Field[] getFields() {
        return (Field[]) fields.toArray();
    }

    @Override
    public String toString() {
        return getDefinition();
    }
    private final String DELIMITER = ",";
    private List<Field> fields;
    private String name;
}
